<?php


namespace app\model;


use app\util\Format;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\concern\SoftDelete;

class SysRole extends Model
{
    use SoftDelete;

    protected $pk = "id";
    protected $readonly = ["id"];
    protected $autoWriteTimestamp = "datetime";

    protected $append = ["menu_tree", "perm_list", "permission"];

    /**
     * 获取菜单列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getMenuTreeAttr(): array
    {
        return Format::list2tree($this->getPermListAttr(), "id", "pid", 0, 1);
    }

    /**
     * 获取权限列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPermListAttr(): array
    {
        return $this->hasManyThrough(SysPerm::class, SysRolePerm::class, "role_id", "id", "id", "perm_id")
            ->where("sys_role_perm.delete_time is null")
            ->order(["sys_perm.sort" => "desc", "sys_perm.create_time" => "asc"])
            ->select()->toArray();
    }

    /**
     * 获取权限节点
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundExceptionhuo
     */
    public function getPermissionAttr(): array
    {
        $list = $this->getPermListAttr();
        $nodes = [];
        foreach ($list as $item) {
            if ($item["perm"]) {
                array_push($nodes, $item["perm"]);
            }
        }
        return $nodes;
    }
}